﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Model;
using NVelocity;
using NVelocity.App;
using Utils;
using Dao;
namespace BO
{
    public  class BaseBO
    {
        public void MakeCode(List<ColumnModel> lst, TableModel table)
        {
        }
        /// <summary>
        /// 生成默认的Java基于hibernate模板
        /// </summary>
        public void MakeCodeForJavaDefaultHib()
        {
            string defaultTemplatePath = SetConfig.GetDefaultTempate();
            string package = SetConfig.GetPackage();
            string folderName = DateTime.Now.ToString("yyyyMMddHH");
            string rootPath = FileHelper.RootPath();
            FileHelper.CreateFloder(rootPath + "/" + folderName);
            IDaoBase dao = new MySqlDaoBase();
            dao.TableName = TableName;
            var tableLst = dao.GetTable();
            var dict = new Dictionary<string, string>();
            dict.Add("list.js", "{tableNameAlias}Manager/js");
            dict.Add("saveOrUpdate.js", "{tableNameAlias}Manager/js");
            dict.Add("view.js", "{tableNameAlias}Manager/js");
            dict.Add("saveOrUpdate.jsp", "{tableNameAlias}Manager");
            dict.Add("list.jsp", "{tableNameAlias}Manager");
            dict.Add("view.jsp", "{tableNameAlias}Manager");
            dict.Add("lan.txt", "{tableNameAlias}Manager");
            dict.Add("{tableNameAlias}.java", "Entity");
            dict.Add("{tableNameAlias}Action.java", "Action");
            foreach (var table in tableLst)
            {
                dao.TableName = table.TableName;
                var lst = dao.GetColumnList();
                foreach (string floders in dict.Select(dic => string.Format("{0}/{1}/{2}", rootPath, folderName, dic.Value.Replace("{tableNameAlias}", table.TableNameAlias))))
                {
                    FileHelper.CreateFloder(floders);
                }
                foreach (var dc in dict)
                {
                    var builder = new StringBuilder();
                    builder.Append(FileHelper.ReadFile(string.Format("{0}/template/{1}/{2}.tpl", FileHelper.RootPath(), defaultTemplatePath, dc.Key)));
                    var content = "false";
                    try
                    {
                        content = SetVelocityEngine(table, lst, package, builder.ToString());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(string.Format("Exception:{0},template:{1},tableName:{2}", ex.Message, dc.Key,
                                                      table.TableName));
                    }
                    if (content == "false")
                    {
                        break;
                    }
                    string fileName = string.Format("{0}/{1}/{2}", rootPath, folderName, dc.Value.Replace("{tableNameAlias}", table.TableNameAlias));
                    fileName = fileName.Replace("{tableNameAlias}", table.TableNameAlias);
                    FileHelper.WriteToFile(content, fileName + "/" + dc.Key.Replace("{tableNameAlias}", table.TableNameAlias), FileMode.Create);
                }
            }
            DialogResult result = MessageBox.Show("代码生成完成");
            if (result == DialogResult.OK)
            {
                Process.Start("Explorer.exe", rootPath + "\\" + folderName + "\\");
            }
        }
        /// <summary>
        /// 基于mybatis的java oa模板
        /// </summary>
        public void MakeCodeForJavaOA()
        {
            string defaultTemplatePath = SetConfig.GetDefaultTempate();
            string package = SetConfig.GetPackage();
            string folderName = DateTime.Now.ToString("yyyyMMddHH");
            string rootPath = FileHelper.RootPath();
            FileHelper.CreateFloder(rootPath + "/" + folderName);
            IDaoBase dao = DaoBase.GetObject();
            dao.TableName = TableName;
            var tableLst = dao.GetTable();
            var dict = new Dictionary<string, string>();
            dict.Add("add.ftl", "{tableNameAlias}");
            dict.Add("edit.ftl", "{tableNameAlias}");
            dict.Add("list.html", "{tableNameAlias}");
            dict.Add("view.html", "{tableNameAlias}");
            dict.Add("lan.txt", "{tableNameAlias}");
            dict.Add("{tableNameAlias}.java", "model");
            dict.Add("{tableNameAlias}.xml", "mapper");
            dict.Add("{tableNameAlias}Controller.java", "controller");
            dict.Add("{tableNameAlias}Bo.java", "bo");
            dict.Add("{tableNameAlias}Dao.java", "dao");
            foreach (var table in tableLst)
            {
                dao.TableName = table.TableName;
                var lst = dao.GetColumnList();
                foreach (string floders in dict.Select(dic => string.Format("{0}/{1}/{2}", rootPath, folderName, dic.Value.Replace("{tableNameAlias}", table.TableNameAlias))))
                {
                    FileHelper.CreateFloder(floders);
                }
                foreach (var dc in dict)
                {
                    var builder = new StringBuilder();
                    builder.Append(FileHelper.ReadFile(string.Format("{0}/template/{1}/{2}.tpl", FileHelper.RootPath(), defaultTemplatePath, dc.Key)));
                    var content = "false";
                    try
                    {
                        content = SetVelocityEngine(table, lst, package, builder.ToString());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(string.Format("Exception:{0},template:{1},tableName:{2}", ex.Message, dc.Key,
                                                      table.TableName));
                        break;
                    }

                    if (content == "false")
                    {
                        break;
                    }
                    string fileName = string.Format("{0}/{1}/{2}", rootPath, folderName, dc.Value.Replace("{tableNameAlias}", table.TableNameAlias));
                    fileName = fileName.Replace("{tableNameAlias}", table.TableNameAlias);
                    FileHelper.WriteToFile(content, fileName + "/" + dc.Key.Replace("{tableNameAlias}", table.TableNameAlias), FileMode.Create);
                }
            }
            DialogResult result = MessageBox.Show("代码生成完成");
            if (result == DialogResult.OK)
            {
                Process.Start("Explorer.exe", rootPath + "\\" + folderName + "\\");
            }
        }
        /// <summary>
        /// 基于mybatis的java模板
        /// </summary>
        public void MakeCodeForJavaDefaultBatis()
        {
            string defaultTemplatePath = SetConfig.GetDefaultTempate();
            string package = SetConfig.GetPackage();
            string folderName = DateTime.Now.ToString("yyyyMMddHH");
            string rootPath = FileHelper.RootPath();
            FileHelper.CreateFloder(rootPath + "/" + folderName);
            IDaoBase dao = DaoBase.GetObject();
            dao.TableName = TableName;
            var tableLst = dao.GetTable();
            var dict = new Dictionary<string, string>();
            //dict.Add("list.js", "js/{tableNameAlias}");
            //dict.Add("saveOrUpdate.js", "js/{tableNameAlias}");
            //dict.Add("view.js", "js/{tableNameAlias}");
            dict.Add("saveOrUpdate.jsp", "{tableNameAlias}Manager");
            dict.Add("list.jsp", "{tableNameAlias}Manager");
            dict.Add("view.jsp", "{tableNameAlias}Manager");
            dict.Add("lan.txt", "{tableNameAlias}Manager");
            dict.Add("{tableNameAlias}.java", "domain");
            dict.Add("{tableNameAlias}.xml", "mapper");
            dict.Add("{tableNameAlias}Action.java", "action");
            dict.Add("{tableNameAlias}Bo.java", "bo");
            dict.Add("{tableNameAlias}Dao.java", "dao");
            foreach (var table in tableLst)
            {
                dao.TableName = table.TableName;
                var lst = dao.GetColumnList();
                foreach (string floders in dict.Select(dic => string.Format("{0}/{1}/{2}", rootPath, folderName, dic.Value.Replace("{tableNameAlias}", table.TableNameAlias))))
                {
                    FileHelper.CreateFloder(floders);
                }
                foreach (var dc in dict)
                {
                    var builder = new StringBuilder();
                    builder.Append(FileHelper.ReadFile(string.Format("{0}/template/{1}/{2}.tpl", FileHelper.RootPath(), defaultTemplatePath, dc.Key)));
                    var content = "false";
                    try
                    {
                        content = SetVelocityEngine(table, lst, package, builder.ToString());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(string.Format("Exception:{0},template:{1},tableName:{2}", ex.Message, dc.Key,
                                                      table.TableName));
                        break;
                    }

                    if (content == "false")
                    {
                        break;
                    }
                    string fileName = string.Format("{0}/{1}/{2}", rootPath, folderName, dc.Value.Replace("{tableNameAlias}", table.TableNameAlias));
                    fileName = fileName.Replace("{tableNameAlias}", table.TableNameAlias);
                    FileHelper.WriteToFile(content, fileName + "/" + dc.Key.Replace("{tableNameAlias}", table.TableNameAlias), FileMode.Create);
                }
            }
            DialogResult result = MessageBox.Show("代码生成完成");
            if (result == DialogResult.OK)
            {
                Process.Start("Explorer.exe", rootPath + "\\" + folderName + "\\");
            }
        }

        /// <summary>
        /// VelocityContext
        /// </summary>
        /// <param name="table"></param>
        /// <param name="lst"></param>
        /// <param name="package"></param>
        /// <returns></returns>
        private string SetVelocityEngine(TableModel table, List<ColumnModel> lst, string package, string content)
        {
            var vltEngine = new VelocityEngine();
            vltEngine.Init();
            var vltContext = new VelocityContext();
            vltContext.Put("table", table);
            vltContext.Put("ColumnList", lst);
            vltContext.Put("Package", package);
            vltContext.Put("Utils", new NvUtils());
            var vltWriter = new StringWriter();
            try
            {
                vltEngine.Evaluate(vltContext, vltWriter, "Log:" + table.TableName, content);
            }
            catch (Exception exception)
            {

                throw exception;
            }
            return vltWriter.GetStringBuilder().ToString();
        }

        /// <summary>
        /// 返回所有表信息
        /// </summary>
        /// <returns></returns>
        public List<TableModel> GetTable()
        {
            IDaoBase dao = DaoBase.GetObject();
            return dao.GetTable();
        }
        public string TableName { get; set; }

 
    }
}
